<template>
  <div class="app-container">
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-suffix=":"
      label-width="auto"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('inventoryOrderLang.inventoryOrderNo')" prop="inventoryOrderNo">
            <el-input
              v-model="queryParams.inventoryNo"
              :placeholder="$t('pleaseEnter')"
              clearable
              filterable
              style="width: 300px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('destructionLang.destructionStatus')" prop="status">
            <el-select
              v-model="queryParams.status"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in inventoryOrderStatusOptions"
                :key="item.value"
                :value="item.value"
                :label="$t('statusLang.' + item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('destructionLang.sku')" prop="sku">
            <el-input
              v-model="queryParams.sku"
              :placeholder="$t('pleaseEnter') + $t('MultipleSpacesSeparated')"
              clearable
              filterable
              style="width: 300px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item prop="dataTime">
            <template #label>
              <el-select
                v-model="queryParams.dateType"
                @change="changeDateType"
              >
                <el-option :value="0" :label="$t('destructionLang.createDate')" />
                <el-option :value="1" :label="$t('inventoryOrderLang.inventorydate')" />
                <el-option :value="2" :label="$t('modifiedDate')" />
              </el-select>
            </template>
            <el-date-picker
              v-model="queryParams.dateTime"
              type="datetimerange"
              value-format="timestamp"
              :range-separator="$t('to')"
              :start-placeholder="$t('beginDate')"
              :end-placeholder="$t('endDate')"
              @change="changeDateTime"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('depotLang.depot')" prop="depotId">
            <el-select
              v-model="queryParams.depotId"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in depotListAllStatusList"
                :key="item.value"
                :value="item.value"
                :label="$t(item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10" />
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          {{ $t("add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleBatchAdd"
        >
          {{ $t("inventoryOrderLang.batchAdd") }}</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      border
      class="mt-10"
    >
      <el-table-column
        :label="$t('tableIndex')"
        type="index"
        :index="indexAdd"
        align="center"
        width="100"
      />
      <el-table-column
        :label="$t('inventoryOrderLang.inventoryOrderNo')"
        prop="inventoryNo"
        align="left"
        min-width="150"
      />
      <el-table-column
        :label="$t('locationTypeLang.depot')"
        prop="depotName"
        align="center"
        min-width="150"
      />
      <el-table-column
        :label="$t('locationTypeLang.locationTypeStatus')"
        prop="depotName"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("destructionLang.destructionStatus") + ":" }}
            <span>{{ $t("statusLang." + getTitleByValue(inventoryOrderStatusOptions, scope.row.status)) }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.date')"
        prop="gmtCreated,firstInventoryTime,gmtModified"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("destructionLang.createDate") + ":" }}
            <span>{{ scope.row.gmtCreated }}</span>
          </p>
          <p>
            {{ $t("inventoryOrderLang.inventorydate") + ":" }}
            <span>{{ scope.row.firstInventoryTime }}</span>
          </p>
          <p>
            {{ $t("destructionLang.lastEditDate") + ":" }}
            <span>{{ scope.row.gmtModified }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('destructionLang.operator')"
        prop="createdUser,firstInventoryUser,modifiedUser"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("cutOffOrderLang.creator") + ":" }}
            <span>{{ scope.row.createdUser
            }}</span>
          </p>
          <p>
            {{ $t("inventoryOrderLang.inventoryUser") + ":" }}
            <span>{{ scope.row.firstInventoryUser
            }}</span>
          </p>
          <p>
            {{ $t("problemItemLang.lastEditor") + ":" }}
            <span>{{ scope.row.modifiedUser
            }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')"
        width="180"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleDetail(scope.row)">
            {{ $t("info") }}
          </el-button>
          <el-button type="text" @click="handleImport(scope.row)">
            {{ $t("goodsSKULang.imports") }}
          </el-button>
          <el-button v-if="isAdmin && scope.row.status===3" type="text" @click="updateInfo(scope.row)">
            {{ $t("edit") }}
          </el-button>
          <el-button v-if="scope.row.status===3" type="text" @click="handleConfirm(scope.row)">
            {{ $t("confirm") }}
          </el-button>
          <el-button v-if="scope.row.status===1" type="text" @click="handleDelete(scope.row)">
            {{ $t("delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layoout="total,prev,pager,next"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
      />
    </el-row>
    <!-- 详情弹层 -->
    <DetailBaseForm
      v-model="detailParams.id"
      :visible.sync="detailDialog"
      :title="title"
      :operation="detailParams.operation"
      @close="close"
    />
    <!-- 新增弹层 -->
    <AddBaseForm
      v-model="addParams.id"
      :visible.sync="addDialog"
      :title="title"
      :operation="addParams.operation"
      @close="closeAdd"
    />
    <!-- 批量新增弹层 -->
    <BatchAddBaseForm
      v-model="batchAddParams.id"
      :visible.sync="batchAddDialog"
      :title="title"
      :operation="batchAddParams.operation"
      @close="closeBatchAdd"
    />
    <el-dialog :title="title" :visible.sync="openDialog" width="1500px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-descriptions :model="form" :title="$t('BasicInformation')">
          <el-descriptions-item :label="$t('inventoryOrderLang.inventoryOrderNo')">{{ form.inventoryNo }}</el-descriptions-item>
          <el-descriptions-item :label="$t('destructionLang.createDate')">{{ form.gmtCreated }}</el-descriptions-item>
          <el-descriptions-item :label="$t('destructionLang.lastEditDate')">{{ form.gmtModified }}</el-descriptions-item>
          <el-descriptions-item :label="$t('destructionLang.destructionStatus')">{{ formattedStatus }}</el-descriptions-item>
          <el-descriptions-item :label="$t('cutOffOrderLang.creator')">{{ form.createdUser }}</el-descriptions-item>
          <el-descriptions-item :label="$t('problemItemLang.lastEditor')">{{ form.firstInventoryUser }}</el-descriptions-item>
          <el-descriptions-item :label="$t('destructionLang.warehouseCode')">{{ form.depotName }}</el-descriptions-item>
        </el-descriptions>
      </el-form>
      <el-table :data="form.detail" style="width: 100%">
        <el-table-column prop="locationCode" :label="$t('locationLang.locationCode')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.locationCode" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="regionName" :label="$t('locationLang.depotRegion')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.regionName" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="containerCode" :label="$t('containerTypeLang.container')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.containerCode" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="skuCode" :label="$t('goodsSKULang.skuCode')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.skuCode" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="declaredName" :label="$t('OMSLang.itemCn')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.declaredName" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="skuNum" :label="$t('inventoryOrderLang.restNum')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.skuNum" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="firstInventoryQty" :label="$t('inventoryOrderLang.firstInventNum')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.firstInventoryQty" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="secondInventoryQty" :label="$t('inventoryOrderLang.againInventNum')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.secondInventoryQty" />
          </template>
        </el-table-column>
        <el-table-column prop="disInventNum" :label="$t('inventoryOrderLang.disInventNum')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.disInventNum" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="inventResult" :label="$t('inventoryOrderLang.inventResult')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.inventoryResult " disabled />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DetailBaseForm from './components/detail.vue'
import AddBaseForm from './components/add-form.vue'
import BatchAddBaseForm from './components/batch-add-form.vue'
import { inventoryOrderStatusOptionDict } from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getDepotList } from '@/api/business/depotManage/depot'
import { deleteInventoryOrder, getInventoryOrderPageList, getInventoryOrderDetail, editInventoryDetail, getUserName } from '@/api/business/operateManage/invetoryOrder'
import XLSX from 'xlsx';

export default {
  name: 'Depot',
  components: { DetailBaseForm, AddBaseForm, BatchAddBaseForm },
  data() {
    return {
      total: 0,
      isAdmin: false,
      loading: false,
      depotListAllStatusList: [], // 仓库列表
      // 表单参数
      form: {},
      // 盘点列表数据
      formDetail: {},
      queryParams: {
        inventoryNo: null,
        status: null,
        depotId: null,
        sku: null,
        pageNo: 1,
        pageSize: 10,
        dateType: 0,
        gmtCreatedStart: null,
        gmtCreatedEnd: null,
        firstInventoryTimeStart: null,
        firstInventoryTimeEnd: null,
        gmtModifiedStart: null,
        gmtModifiedEnd: null,
      },
      tableData: [], // 列表
      getTitleByValue: getTitleByValue,
      inventoryOrderStatusOptions: getDictOptionList(inventoryOrderStatusOptionDict), // 状态
      detailParams: {
        id: null,
        operation: 0
      },
      addParams: {
        id: null,
        operation: 0
      },
      batchAddParams: {
        id: null,
        operation: 0
      },
      detailDialog: false,
      openDialog: false,
      addDialog: false,
      batchAddDialog: false,
      title: ''
    }
  },
  computed: {
    formattedStatus() {
      const status = this.form.status;
      switch (status) {
        case 1:
          return this.$t('statusLang.notInventoryOrder');
        case 2:
          return this.$t('statusLang.needReplay');
        case 3:
          return this.$t('statusLang.needAuditing');
        case 4:
          return this.$t('statusLang.doneInventoryOrder');
        default:
          return 'Unknown status';
      }
    }
  },
  created() {
    this.getInventoryOrderPageList()
    this.getDepotListAllStatus()
    this.getUserName()
  },
  methods: {
    // 重置
    async handleReset() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        inventoryNo: null,
        status: null,
        depotId: null,
        dateType: 0,
      }
      this.getInventoryOrderPageList()
    },
    // 查询
    async handleQuery() {
      this.queryParams.pageNo = 1
      this.getInventoryOrderPageList()
    },
    // 获取数据列表
    async getInventoryOrderPageList() {
      if (this.queryParams.inventoryNo) {
        if (this.queryParams.inventoryNo.includes(' ')) {
          this.queryParams.inventoryNos = []
          // 使用空格将 inventoryNo 分隔成数组
          this.queryParams.inventoryNos = this.queryParams.inventoryNo.split(' ')
          this.queryParams.inventoryNo = null
        } else {
          this.queryParams.inventoryNos = []
        }
      } else {
        this.queryParams.inventoryNo = null
        this.queryParams.inventoryNos = null
      }
      if (this.queryParams.sku) {
        if (this.queryParams.sku.includes(' ')) {
          this.queryParams.skus = []
          // 使用空格将 destroyNo 分隔成数组
          this.queryParams.skus = this.queryParams.sku.split(' ')
          this.queryParams.sku = null
        } else {
          this.queryParams.skus = []
        }
      } else {
        this.queryParams.sku = null
        this.queryParams.skus = null
      }
      this.loading = true
      const res = await getInventoryOrderPageList({ ...this.queryParams })
      if (res.data.inventoryOrderDTOList) {
        this.tableData = res.data.inventoryOrderDTOList
        this.total = res.data.totalRowNum
      } else {
        this.tableData = []
        this.total = 0
      }
      this.loading = false
    },
    // 仓库下拉列表
    async getDepotListAllStatus() {
      const { data } = await getDepotList()
      this.depotListAllStatusList = data
      console.log(data)
    },
    // 新增
    async handleAdd() {
      this.addParams.operation = 1
      this.title = this.$t('add')
      this.addDialog = true
    },
    // 批量创建
    async handleBatchAdd() {
      this.title = this.$t('inventoryOrderLang.batchAdd')
      this.batchAddDialog = true
    },
    // 查看
    async handleDetail(row) {
      this.detailParams.operation = 0
      this.detailParams.id = row.inventoryOrderId
      this.title = this.$t('info')
      this.detailDialog = true
      // setTimeout(() => {
      //   this.detailDialog = true
      // }, 400)
    },
    // 获取用户名名称
    async getUserName() {
      const response = await getUserName();
      this.isAdmin = response.data == '系统管理员';
    },
    async handleImport(row) {
      const { data } = await getInventoryOrderDetail({ inventoryOrderId: row.inventoryOrderId })
      // 创建工作簿
      const workbook = XLSX.utils.book_new();

      // 构建表头
      const header = ['盘点单号', '盘点状态', '仓库', '创建日期', '创建人', '最后修改日期', '盘点日期', '复盘日期', '复盘人', '审核人', '审核日期', '修改人', '库位', '分区', '流装箱', '' +
      'sku', '物品中文名', '库存数量', '一盘数量', '复盘数量', '差异量', '盘点结果'];
      let statusText;
      switch (data.status) {
        case 1:
          statusText = '待盘点';
          break;
        case 2:
          statusText = '需复盘';
          break;
        case 3:
          statusText = '待审核';
          break;
        case 4:
          statusText = '盘点完成';
          break;
        default:
          statusText = '';
      }
      // 构建主表数据行
      const mainDataRow = [
        data.inventoryNo,
        statusText,
        data.depotName,
        data.gmtCreated,
        data.createdUser,
        data.gmtModified,
        data.firstInventoryTime,
        data.secondInventoryTime,
        data.secondInventoryUser,
        data.conformUser,
        data.conformTime,
        data.modifiedUser
      ];
      const sheetData = [header];
      sheetData.push(mainDataRow);
      data.detail.forEach((detail, index) => {
        const detailRow = new Array(header.length).fill(null);
        detailRow[12] = detail.locationCode;
        detailRow[13] = detail.regionName;
        detailRow[14] = detail.containerCode;
        detailRow[15] = detail.skuCode;
        detailRow[16] = detail.declaredName;
        detailRow[17] = detail.skuNum;
        detailRow[18] = detail.firstInventoryQty;
        detailRow[19] = detail.secondInventoryQty;
        let disInventNum;
        let inventoryResult;
        if (data.status === 1) {
          disInventNum = null;
          inventoryResult = this.$t('statusLang.notInventoryOrder');
        } else {
          disInventNum = (detail.secondInventoryQty ? detail.secondInventoryQty : detail.firstInventoryQty) - detail.skuNum;
          if (disInventNum === 0) {
            inventoryResult = this.$t('inventoryOrderLang.inventoryDraw');
          } else if (disInventNum > 0) {
            disInventNum = '+' + disInventNum;
            inventoryResult = this.$t('inventoryOrderLang.inventoryProfit');
          } else {
            inventoryResult = this.$t('inventoryOrderLang.inventoryLoss');
          }
        }
        detailRow[20] = disInventNum;
        detailRow[21] = inventoryResult;
        sheetData.push(detailRow);
      });

      const sheet = XLSX.utils.aoa_to_sheet(sheetData);
      XLSX.utils.book_append_sheet(workbook, sheet, '合并数据');

      const columnWidths = {};
      sheet['!cols'] = [];
      header.forEach((colName, colIndex) => {
        const maxLength = sheetData.reduce((max, row) => Math.max(max, (row[colIndex] || '').toString().length), 0);
        columnWidths[colIndex] = maxLength < 10 ? 10 : maxLength;
        sheet['!cols'].push({ wch: columnWidths[colIndex] });
      });

      // 生成 Excel 文件并触发下载
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '盘点数据详情.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    },
    // 查看
    async handleConfirm(row) {
      this.detailParams.operation = 1
      this.detailParams.id = row.inventoryOrderId
      this.title = this.$t('confirm')
      this.detailDialog = true
      // setTimeout(() => {
      //   this.detailDialog = true
      // }, 400)
    },
    // 修改按钮
    async updateInfo(row) {
      const res = await getInventoryOrderDetail({ inventoryOrderId: row.inventoryOrderId });
      this.openDialog = true;
      this.title = '修改盘点单';
      this.form = res.data;
      // 遍历 detail 数组中的每个元素进行单独计算
      res.data.detail.forEach(item => {
        const secondQty = item.secondInventoryQty || 0;
        const firstQty = item.firstInventoryQty || 0;
        const skuNum = item.skuNum || 0;
        const calculatedDisInventNum = (secondQty || firstQty) - skuNum;
        if (calculatedDisInventNum === 0) {
          item.disInventNum = 0
          item.inventoryResult = this.$t('inventoryOrderLang.inventoryDraw');
        } else if (calculatedDisInventNum > 0) {
          item.inventoryResult = this.$t('inventoryOrderLang.inventoryProfit');
          item.disInventNum = '+' + calculatedDisInventNum;
        } else {
          item.inventoryResult = this.$t('inventoryOrderLang.inventoryLoss');
          item.disInventNum = calculatedDisInventNum.toString();
        }
        if (res.data.status === 1) {
          item.inventoryResult = this.$t('statusLang.notInventoryOrder');
          item.disInventNum = null;
        }
      });
    },
    // 删除
    async handleDelete(row) {
      const flag = await this.$confirm(
        this.$t('inventoryOrderLang.deleteHintDesc'),
        this.$t('inventoryOrderLang.deleteHint') + '?',
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).catch((err) => err)
      if (flag === 'cancel') return
      const res = await deleteInventoryOrder({
        inventoryOrderId: row.inventoryOrderId
      })
      if (res && res.returnCode === 10000) {
        this.$message({
          type: 'success',
          message: this.$t('handleSuccess')
        })
        this.getInventoryOrderPageList()
      }
    },
    async submitForm() {
      const dataToSend = this.form.detail.map(item => ({
        inventoryOrderDetailId: item.inventoryOrderDetailId,
        secondInventoryQty: item.secondInventoryQty
      }));
      const res = await editInventoryDetail(dataToSend)
      if (!res || res.returnCode !== 10000) {
        this.$message({
          type: 'warning',
          message: this.$t('inventoryOrderLang.confirmFail')
        })
      } else {
        this.$message({
          type: 'success',
          message: this.$t('handleSuccess')
        })
      }
      this.openDialog = false;
    },
    // 关闭弹出层
    close() {
      this.detailParams.id = null
      this.detailParams.operation = 0
      this.detailDialog = false
    },
    // 关闭弹出层
    closeAdd() {
      this.addParams.id = null
      this.addParams.operation = 0
      this.addDialog = false
      this.getInventoryOrderPageList()
    },
    // 关闭弹出层
    closeBatchAdd() {
      this.batchAddParams.id = null
      this.batchAddParams.operation = 0
      this.batchAddDialog = false
      this.getInventoryOrderPageList()
    },
    // 切换页码
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.getInventoryOrderPageList()
    },
    indexAdd(index) {
      const page = this.queryParams.pageNo // 当前页码
      const pagesize = this.queryParams.pageSize // 每页条数
      return index + 1 + (page - 1) * pagesize
    },
    // 取消按钮
    cancel() {
      this.openDialog = false;
    },
    // 处理时间戳
    handleTimeStamp(dateTime) {
      const timestamp = dateTime.map((item) => item / 1000)
      if (this.queryParams.dateType === 0) {
        this.queryParams.gmtCreatedStart = timestamp[0]
        this.queryParams.gmtCreatedEnd = timestamp[1]
      } else if (this.queryParams.dateType === 1) {
        this.queryParams.firstInventoryTimeStart = timestamp[0]
        this.queryParams.firstInventoryTimeEnd = timestamp[1]
      } else if (this.queryParams.dateType === 2) {
        this.queryParams.gmtModifiedStart = timestamp[0]
        this.queryParams.gmtModifiedEnd = timestamp[1]
      }
    },
    changeDateTime(dateTime) {
      this.handleTimeStamp(dateTime)
    },
    changeDateType(val) {
      this.handleReset();
      this.queryParams.dateType = val;
    },
  }
}
</script>

<style scss="lang" scoped>
.el-row +.el-row {
  margin-top: 15px;
}
.el-form-item {
  margin-bottom: 15px;
}
.el-input {
  padding: 5px;
}
.el-form-item__label {
  font-size: 14px;
  color: #666;
  font-family: Arial, sans-serif;
}
.el-input {
  font-size: 14px;
  color: #333;
}
</style>
